//
//  CitysHelper.m
//  TUIHelper
//
//  Created by txj on 2017/3/13.
//  Copyright © 2017年 hs. All rights reserved.
//

#import "CitysHelper.h"
#import <sqlite3.h>

@implementation CitysHelper
+ (NSString *) getDatabasePath:(NSString *)dbName {
    BOOL success;
    NSError *error;
    NSFileManager *fileManger = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex: 0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent: dbName];
    success = [fileManger fileExistsAtPath: writableDBPath];
    if (!success) {
        NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: dbName];
        success = [fileManger copyItemAtPath: defaultDBPath toPath: writableDBPath error: &error];
        if (!success) {
            NSAssert1(0, @"faild to create writable database file with message '%@'.", [error localizedDescription]);
        }
    }
    return writableDBPath;
}

+ (NSArray *) selectCitysWithConditions:(NSString *)conditions{
    sqlite3 *db;
    NSString *sqlQuery = [NSString stringWithFormat: @"SELECT * FROM CITYS WHERE %@ ORDER BY PINYIN",conditions];
    
    sqlite3_stmt *statement;
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [paths objectAtIndex:0];
    NSString *database_path = [documents stringByAppendingPathComponent:@"areas.sqlite"];
    
    if (sqlite3_open([database_path UTF8String], &db) != SQLITE_OK) {
        sqlite3_close(db);
        NSLog(@"数据库打开失败");
    }
    
    NSMutableArray *dataArr = [NSMutableArray new];
    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &statement, nil) == SQLITE_OK) {
        while (sqlite3_step(statement) == SQLITE_ROW) {
            NSMutableDictionary *dic = [NSMutableDictionary new];
            char *ID = (char*)sqlite3_column_text(statement, 0);
            char *LName = (char*)sqlite3_column_text(statement, 3);
            char *PARENTID = (char*)sqlite3_column_text(statement, 2);
            char *ZIPCODE = (char*)sqlite3_column_text(statement,6);
            NSString *idStr = [NSString stringWithCString: ID encoding: NSUTF8StringEncoding];
            NSString *lNameStr = [NSString stringWithCString: LName encoding: NSUTF8StringEncoding];
            NSString *parentIdStr = [NSString stringWithCString: PARENTID encoding: NSUTF8StringEncoding];
            NSString *zipCodeStr = [NSString stringWithCString: ZIPCODE encoding: NSUTF8StringEncoding];
            [dic setObject:idStr forKey: @"id"];
            [dic setObject:lNameStr forKey: @"name"];
            [dic setObject:parentIdStr forKey: @"parentId"];
            [dic setObject:zipCodeStr forKey: @"zipCode"];
            [dataArr addObject: dic];
        }
    }
    sqlite3_close(db);
    
    return dataArr;
}

@end
